package com.ll.wechat.base.activity;

import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.iqregister.AccountManager;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.ll.wechat.R;
import com.ll.wechat.base.app.Constant;
import com.ll.wechat.base.net.NetCallBackListener;
import com.ll.wechat.base.net.NetUtil;
import com.ll.wechat.base.utils.thread.ThreadPoolUtil;
import com.ll.wechat.base.utils.widget.LoadingDialog;
import com.ll.wechat.base.utils.widget.LoginEditext;
import com.ll.wechat.base.utils.widget.MyToast;

/**
 * 注册页面
 * 
 * @ClassName: RegisterActivity
 * @author yeliangliang
 * @date 2015-8-20 下午4:52:27
 */
public class RegisterActivity extends BaseActivity implements OnClickListener {

	private String name = "";
	private String passWord = "";
	private LoginEditext edt_name;
	private LoginEditext edt_passWord;
	private Button btn_register;
	private LoadingDialog dialog;// 请求对话框

	@Override
	public void initView() {
		setContentView(R.layout.activity_register);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowHomeEnabled(false);
		setTitle("注册");
		edt_name = (LoginEditext) findViewById(R.id.edt_passName);
		edt_passWord = (LoginEditext) findViewById(R.id.edt_passWord);
		btn_register = (Button) findViewById(R.id.btn_register);
		btn_register.setOnClickListener(this);
	}

	@Override
	public void initData() {
		dialog = new LoadingDialog(this,"加载中");
	}

	/**
	 * 发送注册请求
	 * 
	 * @author yeliangliang
	 * @date 2015-8-20 下午4:53:56
	 * @version V1.0
	 * @return void
	 */
	private void postRegister() {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration
						.builder().setServiceName(Constant.SERVICE_NAME).setHost(Constant.IP)
						.setPort(Constant.LOGIN_PORT).setSecurityMode(SecurityMode.disabled)
						.build();
				AbstractXMPPConnection conn2 = new XMPPTCPConnection(configuration);
				try {
					conn2.connect();
				} catch (Exception e1) {
					e1.printStackTrace();
					handler.obtainMessage(Constant.REQUEST_FAILD, "连接服务器失败").sendToTarget();
				}
				AccountManager manager = AccountManager.getInstance(conn2);
				try {
					manager.createAccount(name, passWord);
				} catch (NoResponseException e) {
					e.printStackTrace();
					handler.obtainMessage(Constant.REQUEST_FAILD, "连接服务器失败").sendToTarget();

					return;
				} catch (XMPPErrorException e) {
					e.printStackTrace();
					handler.obtainMessage(Constant.REQUEST_FAILD, "该账户已存在").sendToTarget();
					return;
				} catch (NotConnectedException e) {
					e.printStackTrace();
					handler.obtainMessage(Constant.REQUEST_FAILD, "连接服务器失败").sendToTarget();
					return;
				}
				handler.obtainMessage(Constant.REQUEST_SUCCESS, "注册成功").sendToTarget();

			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_register:
			name = edt_name.getText().toString();
			passWord = edt_passWord.getText().toString();
			if (TextUtils.isEmpty(name.trim())) {
				edt_name.setError("请输入用户名");
				return;
			}
			if (TextUtils.isEmpty(passWord.trim())) {
				edt_passWord.setError("请输入密码");
				return;
			}
			if (!dialog.isShowing()) {
				dialog.showDialog();
			}
			postRegister();
			break;

		default:
			break;
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.REQUEST_SUCCESS:
				MyToast.showToast(RegisterActivity.this, (String) msg.obj);
				NetUtil.requestLogin(RegisterActivity.this, name, passWord,
						new NetCallBackListener() {
							@Override
							public void responseSuccess(int i, Object o) {
								if (dialog != null) {
									dialog.cancel();
								}
								if (i == Constant.REQUEST_SUCCESS) {
									// 登录成功
									// 跳转到主页
									showActivity(RegisterActivity.this, MainActivity.class);
									finishActivity(RegisterActivity.this);
								}
							}

							@Override
							public void responseFailed(int i) {
								if (dialog != null) {
									dialog.cancel();
								}
								handler.obtainMessage(i).sendToTarget();
							}

							@Override
							public void responseError(int i) {
								if (dialog != null) {
									dialog.cancel();
								}
								handler.obtainMessage(i).sendToTarget();
							}

						});

				break;
			case Constant.REQUEST_FAILD:
				MyToast.showToast(RegisterActivity.this, (String) msg.obj);
				if (dialog != null) {
					dialog.cancel();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finishActivity(RegisterActivity.this);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			finishActivity(RegisterActivity.this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
